package net.aaa.hotel.controller;

import net.aaa.hotel.dao.CustomDao;
import net.aaa.hotel.dao.impl.CustomDaoImpl;
import net.aaa.hotel.entity.Custom;
import net.aaa.hotel.util.TransBean;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

@WebServlet("/custom")
public class CustomController extends HttpServlet {
    private CustomDao dao = new CustomDaoImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=UTF-8");
        String method = req.getParameter("method");
    //    System.out.println(method);
        if (method != null) {
            switch (method) {
                case "login":
                    login(req, resp);
                    break;
                case "add":
                    addCustom(req, resp);
                    break;
                case "exit":
                    exit(req, resp);
                    break;
            }
        }
    }

    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        Custom custom = new Custom();
        TransBean.populate(custom, parameterMap);
    //    System.out.println(custom);
        List<Map> map = dao.fondCustom(custom);

        PrintWriter out = resp.getWriter();
        HttpSession session = req.getSession();

        if (map.size() <= 0) {
//            resp.sendRedirect("coustom/login.jsp");
            out.print("0");
        } else {
            if (map.get(0).get("status").equals(0)) {
                session.setAttribute("cuser", map.get(0));
                out.print("1");
            } else {
                out.print("-1");
            }
        }
    }

    private void addCustom(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        Custom custom = new Custom();
        TransBean.populate(custom, parameterMap);
        int i = dao.addCustom(custom);
        PrintWriter w = resp.getWriter();
        if (i > 0) {
            w.print(1);
        } else {
            w.print(0);
        }
        w.flush();
        w.close();
    }
    private void exit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        HttpSession session = req.getSession();
        session.invalidate();
        resp.sendRedirect("coustom/login.jsp");
    }
}
